package com.liqi.frame.comm.controller.manager;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONArray;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liqi.frame.comm.Constants;
import com.liqi.frame.comm.dto.*;
import com.liqi.frame.comm.enums.MenuLevelEnum;
import com.liqi.frame.comm.enums.MenuTargetEnum;
import com.liqi.frame.comm.enums.ResultEnum;
import com.liqi.frame.comm.service.MenuService;
import com.liqi.frame.comm.service.PermissionService;
import com.liqi.frame.comm.token.TokenUtil;
import com.liqi.frame.comm.util.IdUtil;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @author liqi on 2017/12/27.
 * liqiwork@qq.com
 */
@RestController
@RequestMapping({"/menuManager/ajax", "/menuManager/api"})
public class MenuManagerAjaxController {
    @RequestMapping({"/getMenuTreeByCurrentUser"})
    public HttpResult getMenuTreeByCurrentUser() {
        String userId = TokenUtil.getUserId();
        Set permissionSet = permissionService.findPermissionByUserId(userId);

        List<MenuDto> menuList = menuService.getMenuList();
        Map menusMap = new HashMap();
        List<MenuDto> menuListByUser = new ArrayList<>();
        for (int i = 0; i < menuList.size(); i++) {
            if (permissionSet.contains(menuList.get(i).getMenuKey())) {
                menuListByUser.add(menuList.get(i));
                menusMap.put(menuList.get(i).getId(), menuList.get(i));
            }
        }

        for (int j = 0; j < menuListByUser.size(); j++) {
            if (!"0".equals(menuListByUser.get(j).getParentId())) {
                // 非一级菜单
                MenuDto menu = (MenuDto) menusMap.get(menuListByUser.get(j).getParentId());
                if (menu!=null) {
                    List<MenuDto> menuChildren = menu.getChildren();
                    if (menuChildren==null) {
                        menuChildren = new ArrayList<>();
                    }
                    menuChildren.add(menuListByUser.get(j));
                    menu.setChildren(menuChildren);
                    // 面包屑
                    if (menuListByUser.get(j).getBreadcrumb()==null){
                        List breadcrumbList = new ArrayList();
                        menuListByUser.get(j).setBreadcrumb(breadcrumbList);
                    }
                    menuListByUser.get(j).getBreadcrumb().add(menu.getMenuName());
                    menuListByUser.get(j).getBreadcrumb().add(menuListByUser.get(j).getMenuName());
                }
            }
        }

        List<MenuDto> resultMenuList = new ArrayList<>();
        for (int k = 0; k <menuListByUser.size(); k++) {
            if (menuListByUser.get(k).getLevel()==1) {
                resultMenuList.add(menuListByUser.get(k));
            }
        }

        HttpResult result = new HttpResult(ResultEnum.SUCCESS);
        result.setData(resultMenuList);
        return result;
    }

    @RequiresPermissions(value = {"menuManager:getMenuList", Constants.OPERATION_PASSKEY}, logical = Logical.OR)
    @RequestMapping({"getMenuList"})
    public LayuiTableData getMenuList(@RequestBody Map params) {
        Integer page = (Integer)params.get("page");
        Integer limit = (Integer)params.get("limit");
        String menuName = params.get("menuName")+"";
        PageHelper.startPage(page, limit);
        List<MenuDto> list = menuService.getMenuListWithName(menuName);
        PageInfo<MenuDto> pageInfo = new PageInfo(list);
//        List<MenuDto> list1 = menuService.getMenuListWithName(menuName);
        LayuiTableData result = new LayuiTableData(ResultEnum.SUCCESS);
        result.setCode(0);
        result.setMsg("");
//        result.setCount(list1.size());
        result.setCount(pageInfo.getTotal());
        result.setData(pageInfo.getList());
        return result;
    }

    /**
     * @param menuName 菜单名
     * 将菜单数据组装为树形结构
     * @return 返回数据
     */
//    @RequiresPermissions(value = {"menuManager:getMenuTableTree", "cimrFrame:operation:passkey"}, logical = Logical.OR)
    @RequestMapping({"getMenuTableTree"})
    public HttpResult getMenuTableTree(@RequestBody Map params) {
        String menuName = params.get("menuName")+"";
        HttpResult result = new HttpResult(ResultEnum.SUCCESS);
        List<MenuDto> list = menuService.getMenuListWithName(menuName);
        List<MenuTreeDto> levl1List = new ArrayList<>();
        List<MenuTreeDto> levl2List = new ArrayList<>();
        for (MenuDto mb:list){
            if (mb.getLevel()==1){
                MenuTreeDto mt = new MenuTreeDto();
                mt.setId(mb.getId());
                mt.setName(mb.getMenuName());
                mt.setMenuKey(mb.getMenuKey());
                mt.setParentId(mb.getParentId());
                mt.setOrderId(mb.getOrderId());
                mt.setLevel(mb.getLevel());
                mt.setUrl(mb.getHref());
                if(mb.getTarget().equals("_self")){
                    mt.setTarget("本页面");
                }
                if(mb.getTarget().equals("_blank")){
                    mt.setTarget("新页面");
                }
                if(mb.getComment()==null){
                    mt.setComment("");
                }else{
                    mt.setComment(mb.getComment());
                }
                levl1List.add(mt);
            }
            if (mb.getLevel()==2){
                MenuTreeDto mt = new MenuTreeDto();
                mt.setId(mb.getId());
                mt.setName(mb.getMenuName());
                mt.setMenuKey(mb.getMenuKey());
                mt.setParentId(mb.getParentId());
                mt.setOrderId(mb.getOrderId());
                mt.setLevel(mb.getLevel());
                mt.setUrl(mb.getHref());
                if(mb.getTarget().equals("_self")){
                    mt.setTarget("本页面");
                }
                if(mb.getTarget().equals("_blank")){
                    mt.setTarget("新页面");
                }
                if(mb.getComment()==null){
                    mt.setComment("");
                }else{
                    mt.setComment(mb.getComment());
                }
                levl2List.add(mt);
            }
        }
        for (MenuTreeDto mb1:levl1List){
            List<MenuTreeDto> mb2List = new ArrayList<MenuTreeDto>();
            for (MenuTreeDto mb2:levl2List){
                if (mb1.getId().equals(mb2.getParentId())){
                    mb2List.add(mb2);
                }
            }
            mb1.setChildren(mb2List);
        }
        result.setData(levl1List);
        return result;
    }

    /**
     * 将菜单数据组装为树形结构
     * @param menuName 菜单名
     * @return 返回数据
     */
    @RequestMapping({"getMenuTreeTable"})
    public HttpResult getMenuTreeTable(@RequestBody Map params) {
        String menuName = params.get("menuName")+"";
        HttpResult result = new HttpResult(ResultEnum.SUCCESS);
        List<MenuDto> list = menuService.getMenuListWithName(menuName);
        JSONArray jsonArray = new JSONArray(list);
        result.setData(jsonArray);
        return result;
    }

    @RequestMapping({"getMenuLevelSelect"})
    public HttpResult getMenuLevelSelect(@RequestBody Map params) {
        String level = params.get("level")+"";
        List<SelectDto<String, String>> levelSelectList = new ArrayList<>();
        for (MenuLevelEnum menuLevelEnum : MenuLevelEnum.values()) {
            SelectDto<String, String> selectDto = new SelectDto<>(menuLevelEnum.getName(), menuLevelEnum.getKey());
            if (Objects.equals(level, menuLevelEnum.getKey())) {
                selectDto.setSelected(true);
            }
            levelSelectList.add(selectDto);
        }
        return HttpResult.success(levelSelectList);
    }

    @RequestMapping({"getMenuTargetSelect"})
    public HttpResult getMenuTargetSelect(@RequestBody Map params) {
        String target = params.get("target")+"";
        List<SelectDto<String, String>> targetSelectList = new ArrayList<>();
        for (MenuTargetEnum menuTargetEnum : MenuTargetEnum.values()) {
            SelectDto<String, String> selectDto = new SelectDto<>(menuTargetEnum.getName(), menuTargetEnum.getKey());
            if (Objects.equals(target, menuTargetEnum.getKey())) {
                selectDto.setSelected(true);
            }
            targetSelectList.add(selectDto);
        }
        return HttpResult.success(targetSelectList);
    }

    @RequestMapping({"getMenuParentIdDefaultSelect"})
    public HttpResult getMenuParentIdDefaultSelect() {
        List<SelectDto<String, String>> parentIdSelectList = new ArrayList<>();
        parentIdSelectList.add(new SelectDto<>("主菜单", "0"));
        return HttpResult.success(parentIdSelectList);
    }

    @RequestMapping({"getMenuParentIdSelect"})
    public HttpResult getMenuParentIdSelect(@RequestBody Map params) {
        String parentId = params.get("parentId")+"";
        List<SelectDto<String, String>> parentIdSelectList = new ArrayList<>();
        List<MenuDto> parentList = menuService.getMenuList();
        for (int i=parentList.size()-1; i>=0; i--){
            if (parentList.get(i).getLevel()==1) {
                SelectDto selectDto = new SelectDto<>(parentList.get(i).getMenuName(), parentList.get(i).getId());
                if (Objects.equals(parentId, parentList.get(i).getId())){
                    selectDto.setSelected(true);
                }
                parentIdSelectList.add(selectDto);
            }
        }
        return HttpResult.success(parentIdSelectList);
    }

    /**
     * @param id 菜单id
     *用户编辑菜单（根据ID查询菜单数据，同时查询一级菜单，菜单打开类型的枚举）
     * @return 数据
     */
//    @RequiresPermissions(value = {"menuManager:getMenuInfoById", "cimrFrame:operation:passkey"}, logical = Logical.OR)
    @RequestMapping({"getMenuInfoById"})
    public HttpResult getMenuInfoById(@RequestBody Map params) {
        String id = params.get("id")+"";
        HttpResult result = new HttpResult(ResultEnum.SUCCESS);
        MenuDto menuDto = menuService.getMenuById(id);
        List<MenuDto> parentList = menuService.getMenuList();
        for (int i = parentList.size()-1;i>= 0;i--){
            if (parentList.get(i).getLevel()!=1){
                parentList.remove(i);
            }
        }
        List<MenuTargetDto> MenuTagerList = new ArrayList<>();
        for (MenuTargetEnum menu: MenuTargetEnum.values()){
            MenuTargetDto mtd = new MenuTargetDto();
            mtd.setKey(menu.getKey());
            mtd.setName(menu.getName());
            MenuTagerList.add(mtd);
        }
        Map map = new HashMap();
        map.put("menuDto", menuDto);
        map.put("menuTarget", MenuTagerList);
        map.put("parentList", parentList);
        result.setData(map);
        return result;
    }

    /**
     * 用户新增菜单（查询一级菜单，菜单打开类型的枚举）
     * @return 返回数据
     */
    @RequestMapping({"addMenuInfoById"})
    public HttpResult addMenuInfoById() {
        HttpResult result = new HttpResult(ResultEnum.SUCCESS);
        List<MenuDto> parentList = menuService.getMenuList();
        for (int i = parentList.size()-1;i>= 0;i--){
            if (parentList.get(i).getLevel()!=1){
                parentList.remove(i);
            }
        }
        List<MenuTargetDto> MenuTagerList = new ArrayList<>();
        for (MenuTargetEnum menu:MenuTargetEnum.values()){
            MenuTargetDto mtd = new MenuTargetDto();
            mtd.setKey(menu.getKey());
            mtd.setName(menu.getName());
            MenuTagerList.add(mtd);
        }
        Map map = new HashMap();
        map.put("menuTarget", MenuTagerList);
        map.put("parentList", parentList);
        result.setData(map);
        return result;
    }

    //菜单保存
    @RequiresPermissions(value = {"menuManager:save",
                                  "menuManager:saveMenu",
                                    Constants.OPERATION_PASSKEY}, logical = Logical.OR)
    @RequestMapping({"saveMenu"})
    public HttpResult saveMenu(@RequestBody Map params) {
        String id = null;
        if (ObjectUtil.isNotEmpty(params.get("id"))) {
            id = params.get("id") + "";
        }
        String menuKey = null;
        if (ObjectUtil.isNotEmpty(params.get("menuKey"))) {
            menuKey = params.get("menuKey") + "";
        }
        String menuName = null;
        if (ObjectUtil.isNotEmpty(params.get("menuName"))) {
            menuName = params.get("menuName") + "";
        }
        String parentId = null;
        if (ObjectUtil.isNotEmpty(params.get("parentId"))) {
            parentId = params.get("parentId") + "";
        }
        Object levelObject = params.get("level");
        Integer level = 0;
        if (!Objects.isNull(levelObject)) {
            level = Integer.valueOf(levelObject+"");
        }
        String comment = params.get("comment")+"";
        Object orderIdObject = params.get("orderId");
        Float orderId = new Float(0);
        if (!Objects.isNull(orderIdObject)) {
            orderId = Float.parseFloat(params.get("orderId") + "");
        }
        String target = params.get("target")+"";
        String href = params.get("href")+"";

        int resultStatus1;
        if(id != null && !"".equals(id) && !"null".equals(id)) {
            resultStatus1 =  this.menuService.updateMenu(id, menuKey, menuName, parentId, level, comment, orderId, target, href);
        } else {
            resultStatus1 = this.menuService.insertMenu(IdUtil.getId().toString(), menuKey, menuName, parentId, level, comment, orderId, target, href);
        }

        HttpResult result = new HttpResult(ResultEnum.SUCCESS);
        if(resultStatus1 == 0) {
            result.setCode(ResultEnum.FAILURE.getCode());
        }

        return result;
    }

    //菜单删除
    @RequiresPermissions(value = {"menuManager:delete",
                                  "menuManager:deleteMenu",
            Constants.OPERATION_PASSKEY}, logical = Logical.OR)
    @RequestMapping({"deleteMenu"})
    public HttpResult deleteMenu(@RequestBody Map params) {
        String id = params.get("id")+"";
        String menuKey = params.get("menuKey")+"";
        Object levelObject = params.get("level");
        Integer level = 0;
        if (!Objects.isNull(levelObject)) {
            level = Integer.parseInt(levelObject.toString());
        }

        HttpResult result = new HttpResult(ResultEnum.SUCCESS);
        int resultStatus = 0;
        if(level == 1){
            int resultStatusId = this.menuService.deleteMenuById(id);
            int resultStatusParentId = this.menuService.deleteMenuListByParentId(id);
            resultStatus = resultStatusId+resultStatusParentId;
        }
        if(level==2){
            resultStatus = this.menuService.deleteMenuById(id);
            if(resultStatus == 0) {
                result.setCode(ResultEnum.FAILURE.getCode());
            }
        }
        return result;
    }

    @RequestMapping({"getMenuListByMenuKey"})
    public HttpResult getMenuListByKey(@RequestBody Map params) {
        String menuKey = params.get("menuKey")+"";

        List<MenuDto> list = menuService.getMenuListByKey(menuKey);
        if(list!=null && list.size()>0) {
            return HttpResult.success(list);
        }
        return HttpResult.success(null);
    }

    /**
     * @param id 菜单id
     * @param menuKey 菜单关键字
     * 在编辑时通过menuKey查询菜单，并排除出当前的menuKey的菜单
     */
    @RequestMapping({"getMenuListByMenuKeyOutCurrent"})
    public HttpResult getMenuListByMenuKeyOutCurrent(@RequestBody Map params) {
        String id = params.get("id")+"";
        String menuKey = params.get("menuKey")+"";

        List<MenuDto> list = menuService.getMenuListByKey(menuKey);
        HttpResult result = new HttpResult(ResultEnum.SUCCESS);
        if(list!=null && list.size()!=0){
            if (list.get(0).getId().equals(id)){
                result.setData(null);
            }else {
                result.setData(list);
            }
        }else{
            result.setData(null);
        }
        return result;
    }

    @Autowired
    private MenuService menuService;
    @Autowired
    private PermissionService permissionService;
}
